
import { create } from "zustand";
import { registerFetch,loginFetch,getUserInfoFetch } from "@/apis/user";

type TUserInfo = {
    userId: string;
    userName: string;
    avatar: string;
}
interface UserStore {
  userInfo: TUserInfo | null;
  registerAction: (payload: {username: string, password: string}) => void;
  loginAction: (payload: {username: string, password: string}) => void;
}

export const useUserStore = create<UserStore>((set) => ({
  userInfo: null,
  registerAction: async (payload: {username: string, password: string}) => {
    registerFetch(payload).then((res) => {
      console.log(res);
    });
  },
  loginAction: (payload: {username: string, password: string}) => {
      return new Promise((resolve,reject) => {
        loginFetch(payload).then((res) => {
          if (res.status) {
            localStorage.setItem('token', res.data.token);
            set({ userInfo: res.data.user });
            resolve(res.data.user);
          } else {
            reject(res.msg);
          }
        }).catch((err) => {
            reject(err);
        })
    })
  },
  getUserInfoAction: () => {
    getUserInfoFetch().then((res) => {
      set({ userInfo: res.data });
    });
  }
}));

